import random
from django import http
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from django.views import View
# 图形验证码GET
from django_redis import get_redis_connection

from apps.verifications import constants
from libs.captcha.captcha import captcha

# 获取短信验证码
from meiduo_mall.settings.dev import logger
from utils.response_code import RETCODE


class SMSCodeView(View):
    def get(self, request, mobile):
        # 1.解析校验参数--mobile 不用校验
        uuid = request.GET.get('image_code_id')
        image_code = request.GET.get('image_code')

        # 2.校验图形验证码 如果正确 发送验证码, 不正确 直接返回
        # 2.1 根据uuid 去redis数据库查询 图片验证码
        image_redis_client = get_redis_connection('verify_image_code')
        redis_img_code = image_redis_client.get('img_%s' % uuid)

        # 判断服务器返回的验证
        try:
            if not redis_img_code:
                return JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码失效了'})
            # 如果有值 删除redis服务器上的图形验证码
            if redis_img_code.decode().lower() != image_code.lower():
                return JsonResponse({'code': RETCODE.IMAGECODEERR, 'errmsg': '图形验证码错误'})

            image_redis_client.delete('img_%s' % uuid)
        except Exception as e:
            logger.error(e)
        # 0.避免频繁发送短信
        sms_redis_client = get_redis_connection('sms_code')
        # 1.取出redis保存发短信的标识
        send_flag = sms_redis_client.get('send_flag_%s' % mobile)
        # 2.判断有还是没有
        # 3.有返回太频繁
        if send_flag:
            return http.JsonResponse({'code': RETCODE.THROTTLINGERR, 'errmsg': '发送短信过于频繁'})
        # 4.没有，发送短信，给redis设置标识

        # 3.生成短信验证码,redis-存储
        sms_code = "%06d" % random.randint(0, 999999)
        try:
            p1 = sms_redis_client.pipeline()
            p1.setex('send_flag_%s' % mobile, constants.SMSCODE_SEND_TIME, 1)
            p1.setex("sms_%s" % mobile, constants.SMSCODE_EXPIRE_TIME, sms_code)
            p1.execute()
        except Exception as e:
            logger.error(e)
        # 4.让第三方 容联云-给手机号-发送短信---celery异步发送
        from celery_tasks.sms.tasks import send_sms_code
        send_sms_code.delay(mobile, sms_code)

        return JsonResponse({'code': '0', 'errmsg': '发送短信成功'})


# 获取图形验证码
class ImageCodeView(View):
    """图形验证码"""

    def get(self, request, uuid):
        # 生成图片验证码
        from libs.captcha.captcha import captcha
        text, image = captcha.generate_captcha()

        # 保存图片验证码
        from django_redis import get_redis_connection
        redis_client = get_redis_connection('verify_image_code')
        redis_client.setex('img_%s' % uuid, 300, text)

        # 响应图片验证码
        return http.HttpResponse(image, content_type='image/jpeg')
